<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="op2-file-analysis__main">
    <div class="query">
      <el-form inline ref="queryFormRef" :model="queryParams" label-width="120px" size="small">
        <el-form-item label="任务创建日期:">
          <el-date-picker
            v-model="dateRangeCreateTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="部段名称：">
          <el-select v-model="queryParams.sectionName" clearable placeholder="请选择部段名称">
            <el-option v-for="(item, index) in sectionList" :label="item.name" :value="item.name" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="query_btns">
          <el-button size="small" type="primary" icon="search" @click="doQuery">查询</el-button>
          <el-button size="small" type="default" icon="refresh" @click="doReset">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- <div class="return_btn">
        <el-tooltip content="返回"><img :src="back" alt="" @click="goBack" /></el-tooltip>
      </div> -->
    </div>
    <div class="table_div">
      <el-button size="small" type="primary" class="upload_btn" plain icon="Plus" @click="handleVisible('import')"
        >创建新的结果文件分析事项</el-button
      >
      <el-table :data="tableData" v-loading="loading">
        <el-table-column label="分析事项创建日期" align="left" prop="createTime" fixed="left"></el-table-column>
        <el-table-column label="事项名称" align="left" prop="taskName"></el-table-column>
        <el-table-column label="所属部段" align="left" prop="sectionNames">
          <template #default="scope">
            <span>{{ scope.row.sectionNames && scope.row.sectionNames.length > 0 && scope.row.sectionNames.join('，') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分析状态" align="left" prop="status"> 
          <template #default="scope">
            <span>{{ statusMap[scope.row.status] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="对比结果" align="left" prop="status"> 
          <template #default="scope">
            <!-- <span>{{ statusMap[scope.row.status] }}</span>
            <el-link type="success">success</el-link>  -->
            <!-- <el-popover
              v-if="scope.row.status == 'failed'"
              placement="top-start"
              title="失败原因"
              :width="200"
              trigger="hover"
              :content="scope.row.message"
            >
              <template #reference> -->
                <el-link :type="linkTypeMap[scope.row.status]" @click="openFaultMsg(scope.row)">{{ statusMap[scope.row.status] }}</el-link>
              <!-- </template>
            </el-popover> -->
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" width="200">
          <template #default="scope">
            <el-button v-if="scope.row.status == 'edit' || scope.row.status == 'failed'" size="small" link type="primary" icon="View" @click="editCurrentRecord(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.status == 'completed'" size="small" link type="primary" icon="View" @click="viewAnalysisReport(scope.row)">查看分析报告</el-button>
            <el-button size="small" link type="primary" icon="View" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagenation">
        <!-- <el-pagination
          v-show="total > 0"
          layout="prev, pager, next,jumper"
          v-model:page="queryParams.pageQuery.pageNum"
          v-model:limit="queryParams.pageQuery.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
        /> -->
        <pagination
          v-show="total > 0"
          style="margin-top: 0;"
          v-model:page="queryParams.pageQuery.pageNum"
          v-model:limit="queryParams.pageQuery.pageSize"
          :total="total"
          :background="false"
          layout="total, sizes, prev, pager, next, jumper"
          @pagination="handleCurrentChange"
        />
      </div>
    </div>
  </div>
  <AnalysisDetails v-if="dialogVisible" :dialogVisible="dialogVisible" :rowData="rowData" @handleEvent="handleEvent" />
</template>
<script setup>
const linkTypeMap = {'edit': 'primary', 'in_progress': 'warning', 'completed': 'success', 'failed': 'danger'}
const statusMap = {'edit': '草稿', 'in_progress': '对比中', 'completed': '对比完成', 'failed': '对比失败'}
import AnalysisDetails from './AnalysisDetails.vue';
import { ref, onMounted } from 'vue';
import back from '@/assets/images/back.svg';
import { getOp2CompareTaskList, deletOp2eCompareTask, getAllSectionNames } from '@/api/dataAcquisition';
// import AllFileView from './AllFileView.vue';
const emits = defineEmits(['handleEvent']);
const props = defineProps(['tableName']);
const { proxy } = getCurrentInstance();
const tableData = ref([]);
const dialogVisible = ref(false);
const fileId = ref(null);
const fileRow = ref([]);
const addVisible = ref(false);
const modelList = ref([]);
const preViewVisible = ref(false);
const preViewParams = ref();
const dateRangeCreateTime = ref(['', '']);
const currentChooseId = ref('');
const treeData = ref([]);
const sectionList = ref([]);
const queryParams = ref({
  sectionName: '',
  startCreateTime: '',
  endCreateTime: '',
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 'createTime',
    isAsc: 'descending'
  }
});
const modelNumberList = ref([]);
const batchList = ref([]);
const total = ref(0);
const uploadOp2Visible = ref(false);
const currentRow = ref(null);
const resultList = ref([]);
const loading = ref(false);
const rowData = ref({});
const handleCurrentChange = () => {
  doQuery();
};
const viewAnalysisReport = (row) => {
  rowData.value = row;
  dialogVisible.value = true;
};
const openFaultMsg = (row) => {
  if (row.status !== 'failed') return;
  ElMessageBox.alert(row.message, '失败信息', {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: 'OK',
    callback: (action) => {
      // ElMessage({
      //   type: 'info',
      //   message: `action: ${action}`,
      // })
    },
  })
}
// 回调函数
const handleEvent = (data) => {
  if (data?.type === 'refresh') {
    doQuery();
    dialogVisible.value = false;
  } else if (data?.type === 'cancel') {
    dialogVisible.value = false;
  }
};
const editCurrentRecord = (row) => {
  emits('handleEvent', { component: 'Step', sectionList: sectionList.value, rowId: row._id });
};
//查询数据列表
const doQuery = () => {
  loading.value = true;
  tableData.value = [];
  queryParams.value.startCreateTime = dateRangeCreateTime.value[0];
  queryParams.value.endCreateTime = dateRangeCreateTime.value[1];
  getOp2CompareTaskList(queryParams.value)
    .then((res) => {
      // 处理数据
      loading.value = false;
      total.value = res?.total;
      tableData.value = res.rows;
    })
    .catch(() => {
      loading.value = false;
    })
    .finally(() => {
      loading.value = false;
    });
};
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
};

const doReset = () => {
  queryParams.value = {
    sectionName: '',
    startCreateTime: '',
    endCreateTime: '',
    pageQuery: {
      pageNum: 1,
      pageSize: 10,
      orderByColumn: 'createTime',
      isAsc: 'descending'
    }
  };
  dateRangeCreateTime.value = ['', ''];
  doQuery();
};
// 打开弹窗方法
const handleVisible = (param, data) => {
  if (param == 'import') {
    emits('handleEvent', { component: 'Step', sectionList: sectionList.value, rowId: null });
  }
};

//删除
const handleDelete = (row) => {
  const infoMsg = '确认删除该条数据？';
  ElMessageBox.confirm(infoMsg, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deletOp2eCompareTask(row._id)
    .then((res) => {
      if (res) {
        ElMessage({ showClose: true, message: '删除成功。', type: 'success' });
        doQuery();
      }
    })
    .catch(() => {
      ElMessage({ showClose: true, message: '删除失败。', type: 'error' });
    });
  });
};
onMounted(() => {
  getAllSectionNames({filterSection: true}).then((res) => {
    sectionList.value = res.data;
  });
  doQuery();
});
</script>
<style lang="scss" scoped>
.op2-file-analysis__main {
  // display: flex;
  padding: 20px 5px 20px 20px;
  .query {
    position: relative;
    border: 1px solid #dddddd7a;
    padding: 20px 10px 0 10px;
    .query_btns {
      padding-left: 100px;
    }
    .return_btn {
      position: absolute;
      top: 30px;
      right: 30px;
      // width: 100%;
      > img {
        height: 45px;
        width: 45px;
        margin-left: 10px;
        cursor: pointer;
      }
    }
  }
  .table_div {
    margin-top: 10px;
    border: 1px solid #dddddd7a;
    padding-bottom: 10px;
    .upload_btn {
      margin: 10px 10px;
    }
    .pagenation {
      display: flex;
      justify-content: end;
      margin-top: 10px;
    }
  }
  :deep(.el-form-item__content) {
    width: 220px;
  }
  :deep(.el-tree-node__label) {
    font-size: 12px;
    color: #606266;
  }
}
</style>
